<template>
<div>

<el-row>
	<el-col :span="24">
		<span class="h2">票种列表</span>
		<span class="h4 info ml10">产品包含的门票，如果是套票产品请添加多个票种，用来多次核销，
		例如：A门票，B门票，观光车票等等。</span>
	</el-col>
</el-row>

<div class="ticket mt10 mb10">
<el-collapse v-model="activeName" accordion style="border:none;">
  <el-collapse-item v-for="(item, index) in ticketlist" :name="index">
  	<template slot="title">
      	{{item.name}} 
      	<el-tag type="info" class="ml10">
      		有效期：{{item.periodstart}} 至 {{item.periodend}}
      	</el-tag>
    </template>

    <el-form :ref="'ticket' + index" :rules="rules" :model="item" class="mt20" 
    label-width="180px">

		<el-form-item label="票种名称：" prop="name" >
			<el-input v-model="item.name" placeholder="请输入票种名称" style="width:350px;"></el-input>
		</el-form-item>


		<el-form-item label="有效期："  >
			<daterange  
		    v-bind:se.sync="item.se" 
		    type='daterange'
		    ></daterange>
		</el-form-item>

		<!-- <el-form-item label="是否需要预约：" >
		    <el-switch v-model="item.appoint"
		    active-value="1" inactive-value="0"></el-switch>
		</el-form-item> -->

		<el-form-item v-if="item.id == undefined" 
		label="所属商家：" prop="place_code">
		  	<el-select v-model="item.place_code" filterable placeholder="请选择商家"
		  	style="width:250px;">
			    <el-option
			      v-for="item in bussinesslist"
			      :key="item.code"
			      :label="item.name"
			      :value="item.code">
			    </el-option>
			</el-select>
			<el-button @click="createBussiness">创建商家</el-button>
		</el-form-item>


		<el-form-item v-if="item.id != undefined"  label="商家信息：">
			<el-collapse accordion>
			  <el-collapse-item 
			  v-for="(bussiness, index1) in item.placelist"
			  :name="'bussiness' + index1">
			  	<template slot="title">
			  		{{bussiness.name}}
			  	</template>

			  	<el-form :ref="'bussiness' + index"
			  	:model="bussiness" class="mt20" 
			    label-width="180px">

			    	<bussiness v-bind:bussinessDetail="bussiness"
			    	v-on:save-success="createBussinessSuccess"
			    	></bussiness>
				
					<el-form-item label="核销设备："  >
						<div v-for="(device, index2) in bussiness.devicelist"
						class="device" 
						@click="updateDevice(bussiness.code, device)"
						>
							设备号：{{device.code}} , 设备密码：{{device.pas}}
						</div>
					</el-form-item>

					<el-form-item class="mt10">
					     <el-button type="success" @click="createDevice(bussiness.code, bussiness.devicelist)">为该商家添加一台核销设备</el-button>
					</el-form-item>

				</el-form>

			  </el-collapse-item>
			 
			</el-collapse>

		</el-form-item>

		<el-form-item>
		    <el-button type="primary" 
		    @click="saveTicket(item, 'ticket' + index)">确认票种修改</el-button>
		    <el-button type="danger" 
		    @click="delTicket(item, index)">删除</el-button>
		</el-form-item>
		
	</el-form>
  </el-collapse-item>
  
</el-collapse>
</div>

<el-button type="primary" size="medium" class="mt20" 
v-show="(productDetail.product_attr_sub == '1' && productDetail.ticketlist.length < 1) || productDetail.product_attr_sub == '2'"
@click="createTicket()">添加一个票种</el-button>


<el-dialog title="创建商家" :visible.sync="bussinessVisible">
  	<bussiness v-on:save-success="createBussinessSuccess"></bussiness>
</el-dialog>


<el-dialog title="设备信息" :visible.sync="deviceVisible">
  	<device v-on:save-success="createDeviceSuccess" 
  	v-bind:placeCode="placeCode"
  	v-bind:deviceData="deviceData"
  	></device>
</el-dialog>


</div>		
</template>

<script>

import { mapGetters } from 'vuex'
import daterange from '../../../components/daterange'
import { date2str } from '../../../config/util'
import bussiness from '../../bussiness'
import device from '../../device'

export default {
	name: 'ticket',
	data () {
		return {
		  	activeName : -1,
		  	//ticketlist : this.productDetail.ticketlist,
		  	//se : [new Date(), new Date()],
		  	rules: {
				name: [
				{ required: true, message: '请输入票种名称', trigger: 'blur' },
				{ min: 3, max: 25, message: '长度在 3 到 25 个字符', trigger: 'blur' }
				],

				place_code : [
					{ 
						required: true, 
						message: '请选择一个商家', 
						trigger: 'change' 
					},
				]
	        },

	        bussinessVisible : false,

	        deviceVisible : false,

	        placeCode : '',

	        deviceData : {},
		}
	},

	props: {
		productDetail : Object,
	},

	components: {
		daterange,
		bussiness,
		device,
	},

	computed : {
		...mapGetters([
			'bussinesslist',
		]),

		ticketlist () {
			var arr = this.productDetail.ticketlist;
			for(var i = 0; i < arr.length; i++){
				var tmp = arr[i];
				tmp['se'] = [tmp.periodstart, tmp.periodend];
			}
			return arr;
		},
	},

	methods : {
		onSubmit () {

		},

		saveTicket (item, formName) {
			this.$refs[formName][0].validate((valid) => {

		        if (valid) {
		            var para = {
						code : this.productDetail.code, 
						name : item.name, 
						periodstart : item.se[0], 
						periodend : item.se[1], 
						appoint : item.appoint, 
						cb : res => {
							this.$notify({
					          title: '成功',
					          message: '保存成功',
					          type: 'success'
					        });

					        this.$emit('reload');
						},
						err : res => {
							this.$notify({
					          title: '保存失败',
					          message: res,
					          type: 'error'
					        });
						}
					};

					//创建票种
					if(item.id == undefined){
						para['place_code'] = item.place_code;
					}else{	//编辑票种
						para['id'] = item.id;
					}

					this.$store.dispatch('updateTicket', para);
		        } else {
		            console.log('error submit!!');
		            return false;
		        }
	        });
		},


		createTicket () {
			var obj = {
				code : this.productDetail.code, 
				name : '',
				periodstart : date2str(new Date()),
				periodend : (new Date()).getFullYear() + '-12-31',
				se : [this.periodstart, this.periodend],
				appoint : '0',
			};

			this.ticketlist.push(obj);
			this.activeName = this.ticketlist.length - 1;
		},

		saveBussiness () {

		},

		createBussiness () {
			this.bussinessVisible = true;
		},

		createDevice (placecode, devicelist) {
			this.placeCode = placecode;
			var obj = {
				code : '',
				pas : '',
			};
			this.deviceData = obj;
			devicelist.push(obj);
			this.deviceVisible = true;
		},

		updateDevice (placecode, device) {
			this.placeCode = placecode;
			this.deviceData = device;
			this.deviceVisible = true;
		},

		createDeviceSuccess () {
			this.$notify({
	          title: '成功',
	          message: '操作成功',
	          type: 'success'
	        });
	        this.deviceVisible = false;
		},

		delTicket (item, index) {
			this.$confirm('此操作将永久删除该票种, 是否继续?', '提示', {
	          confirmButtonText: '确定',
	          cancelButtonText: '取消',
	          type: 'warning'
	        }).then(() => {
	          	this.$store.dispatch('deleteTicket', {
	          		id : item.id,
	          		cb : () => {
	          			this.ticketlist.splice(index, 1);
	          		}
	          	});
	        }).catch(() => {
	        });
		},

		createBussinessSuccess () {
			this.$store.dispatch('getBussinessList');
			this.$notify({
	          title: '成功',
	          message: '操作成功',
	          type: 'success'
	        });
	        this.bussinessVisible = false;
		},


	},

	watch : {
	    
	},

	mounted () {
		
		this.$store.dispatch('getBussinessList');
	},

}
</script>

<style scoped>
.device {
	height: 48px;
    line-height: 48px;
    color: #303133;
    cursor: pointer;
    border-bottom: 1px solid #ebeef5;
    font-size: 13px;
    font-weight: 500;
    -webkit-transition: border-bottom-color .3s;
    transition: border-bottom-color .3s;
    outline: 0;
}

.ticket {
	border: 1px solid #ebeef5;
	padding: 0 20px;
}
</style>
